package com.starblink.search.category.ui.main

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.config.StorageKeys
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.storage.SkStorage
import com.starblink.rocketreserver.FetchCategoryRecommendQuery
import com.starblink.rocketreserver.FetchSaleZoneForegroundCategoryQuery
import com.starblink.rocketreserver.fragment.CategoryF
import com.starblink.rocketreserver.type.CategoryRecommendReq
import com.starblink.rocketreserver.type.SaleZoneCategoryReq
import com.starblink.search.category.data.CategoryLevelEnum
import kotlinx.coroutines.launch

class CateMainVM : BaseViewModel() {

    val contentLD = MutableLiveData<List<CategoryF>>()

    internal fun loadIniData() {
        viewModelScope.launch {
            var list: MutableList<CategoryF> = mutableListOf()

            val saleZoneCategory = SkGqlClient.skQuery(
                FetchSaleZoneForegroundCategoryQuery(
                    params = SaleZoneCategoryReq(
                        level = Optional.present(0),
                    )
                )
            )?.data?.fetchSaleZoneForegroundCategory?.map {
                val categoryD = it.categoryD
                CategoryF(
                    categoryD.id,
                    categoryD.name,
                    categoryD.level,
                    categoryD.imageUrl,
                    categoryD.littleImageUrl,
                    categoryD.existsLowerLevel,
                    categoryD.iconUrl,
                    categoryD.traceId,
                    categoryD.traceInfo,
                    categoryD.highestDiscountInfo
                )
            }

            if (saleZoneCategory?.isNotEmpty() == true) {
                val categoryF = CategoryF("0", "Sales Zone", 1, "", "", true, "", "", "", "")
                list.add(categoryF)
            }
//            Log.e("CateMainVM", "======$saleZoneCategory")
            SkStorage.put(StorageKeys.SEARCH_SALE_ZONE, saleZoneCategory?.isNotEmpty() == true)
//            SkStorage.put(StorageKeys.SEARCH_SALE_ZONE, true)

            val oneCateList = SkGqlClient.skQuery(
                FetchCategoryRecommendQuery(
                    params = CategoryRecommendReq(
                        foregroundCategoryId = "0".optional(),
                        scene = CategoryLevelEnum.ONE.level.optional(), //# 场景 1：查询一级前台类目 3：查询三级前台类目
                    )
                )
            )?.data?.fetchCategoryRecommend?.map { it.categoryF }

            if (oneCateList?.isNotEmpty() == true) {
                list.addAll(oneCateList)
            }

            contentLD.postValue(list)
        }
    }

}